package cr

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/apms"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gins/middleware"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/loggers"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/gqlgen/mgr"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"github.com/99designs/gqlgen/graphql/playground"
	"github.com/gin-gonic/gin"
	"github.com/rs/cors"
	ginCors "github.com/rs/cors/wrapper/gin"
	"go.uber.org/zap"
	"net"
	"net/http"
	"time"
)

// 初始化Gqlgen
func GqlgenInit(ctx context.Context, errCh chan error) {
	config := instance.GetConfig()
	httpAddress := config.Gql.Address
	httpListener, err := net.Listen("tcp", httpAddress)
	asserts.Nil(err, err)
	// gin设置
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	// 设置通用中间件
	router.Use(loggers.RecoveryWithZap(true))
	router.Use(apms.OpenTracingMiddleware(instance.GetAppName()))
	//router.Use(auths.RbacAuthMiddle(instance.GetAuthViper()))
	router.Use(middleware.GinContextToContextMiddleware())
	router.Use(loggers.Ginzap(time.RFC3339, true))

	// 跨域配置
	corsOptions := cors.Options{AllowedOrigins: config.Gql.Cors.AllowedOrigins, AllowedHeaders: config.Gql.Cors.AllowedHeaders}
	router.Use(ginCors.New(corsOptions))
	// 注册路由
	gqlRouterRegister(ctx, router)
	// http启动
	go func() {
		loggers.Info("gql启动", ctx, zap.String("监听地址", httpAddress))

		errCh <- router.RunListener(httpListener)
	}()
}

// 路由注册
func gqlRouterRegister(ctx context.Context, router *gin.Engine) {
	// 初始化gqlgen handler

	router.GET("play", playgroundHandler())
	router.StaticFS("/web", http.Dir("/app/html"))
	mgrHandler := mgr.NewGqlHandler()
	router.Any("bi/mgr/gql", mgrHandler)

}

func playgroundHandler() gin.HandlerFunc {
	h := playground.Handler("GraphQL", "/bi/mgr/gql")

	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}
